<!-- src/views/teacher/ReportReview.vue -->
<template>
  <div class="report-review">
    <div class="header">
      <el-page-header @back="$router.go(-1)" title="返回">
        <template #content>
          <span class="title">实习报告审核</span>
        </template>
      </el-page-header>
    </div>

    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索学生姓名或报告标题"
            clearable
            @clear="resetSearch"
            @keyup.enter="fetchReports"
          >
            <template #append>
              <el-button icon="Search" @click="fetchReports" />
            </template>
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-select
            v-model="searchParams.reportType"
            placeholder="报告类型"
            clearable
            @change="fetchReports"
          >
            <el-option label="全部" value="" />
            <el-option label="周志" :value="1" />
            <el-option label="实习报告" :value="2" />
            <el-option label="成果展示" :value="3" />
          </el-select>
        </el-col>

        <el-col :span="6">
          <el-select
            v-model="searchParams.status"
            placeholder="审核状态"
            clearable
            @change="fetchReports"
          >
            <el-option label="全部" value="" />
            <el-option label="待审核" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-col>

        <el-col :span="6">
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-table
        :data="reports"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="studentName" label="学生姓名" width="100" />
        <el-table-column prop="title" label="报告标题" min-width="180" />
        <el-table-column prop="typeName" label="报告类型" width="100" />
        <el-table-column prop="submittedAt" label="提交时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.submittedAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getReportStatusType(scope.row.status)">
              {{ getReportStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewReportDetail(scope.row)">查看详情</el-button>
            <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="primary"
              @click="reviewReport(scope.row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        class="pagination"
      />
    </el-card>

    <!-- 报告详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="报告详情"
      width="700px"
    >
      <div v-if="selectedReport" class="report-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报告标题">{{ selectedReport.title }}</el-descriptions-item>
          <el-descriptions-item label="学生姓名">{{ selectedReport.studentName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ selectedReport.studentId }}</el-descriptions-item>
          <el-descriptions-item label="报告类型">{{ getReportTypeLabel(selectedReport.type) }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatDate(selectedReport.submittedAt) }}</el-descriptions-item>
          <el-descriptions-item label="报告状态">
            <el-tag :type="getReportStatusType(selectedReport.status)">
              {{ getReportStatusLabel(selectedReport.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核时间" v-if="selectedReport.reviewedAt">
            {{ formatDate(selectedReport.reviewedAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="拒绝原因" v-if="selectedReport.rejectReason">
            {{ selectedReport.rejectReason }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="content-section" v-if="selectedReport.content">
          <h3>报告内容</h3>
          <div class="report-content">{{ selectedReport.content }}</div>
        </div>

        <div class="file-section" v-if="selectedReport.fileUrl">
          <h3>附件</h3>
          <el-link :href="selectedReport.fileUrl" target="_blank">下载附件</el-link>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="审核报告"
      width="500px"
    >
      <el-form
        :model="reviewForm"
        :rules="reviewRules"
        ref="reviewFormRef"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="reviewForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="reviewForm.status === 2"
          label="拒绝原因"
          prop="rejectReason"
        >
          <el-input
            v-model="reviewForm.rejectReason"
            type="textarea"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>

        <el-form-item label="评语" prop="comment">
          <el-input
            v-model="reviewForm.comment"
            type="textarea"
            placeholder="请输入评语"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitReview"
            :loading="reviewLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useTeacherStore } from '../../store/teacher'
import { ElMessage } from 'element-plus'

const teacherStore = useTeacherStore()

const reports = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const reviewDialogVisible = ref(false)
const reviewLoading = ref(false)
const selectedReport = ref(null)

// 搜索参数
const searchParams = reactive({
  keyword: '',
  reportType: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 审核表单
const reviewForm = reactive({
  status: 1,
  rejectReason: '',
  comment: ''
})

// 表单验证规则
const reviewRules = {
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  rejectReason: [
    {
      required: true,
      message: '请输入拒绝原因',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (reviewForm.status === 2 && !value) {
          callback(new Error('请输入拒绝原因'))
        } else {
          callback()
        }
      }
    }
  ]
}

const reviewFormRef = ref()

// 获取报告列表
const fetchReports = async () => {
  loading.value = true
  try {
    // 首先获取指导的所有学生
    const internshipsResponse = await teacherStore.getGuidedInternships()
    const studentIds = internshipsResponse.content.map(item => item.studentId)

    // 获取所有学生的材料
    let allMaterials = []
    for (const studentId of studentIds) {
      const materialsResponse = await teacherStore.getStudentMaterials(studentId)
      const materials = materialsResponse.content || materialsResponse
      // 为每个材料添加学生姓名
      const materialsWithStudentName = materials.map(material => {
        const internship = internshipsResponse.content.find(item => item.studentId === studentId)
        return {
          ...material,
          studentName: internship ? internship.studentName : '未知学生',
          typeName: getReportTypeLabel(material.type)
        }
      })
      allMaterials = allMaterials.concat(materialsWithStudentName)
    }

    // 应用搜索过滤
    let filteredMaterials = allMaterials
    if (searchParams.keyword) {
      filteredMaterials = filteredMaterials.filter(material =>
        material.studentName.includes(searchParams.keyword) ||
        material.title.includes(searchParams.keyword)
      )
    }

    if (searchParams.reportType) {
      filteredMaterials = filteredMaterials.filter(material =>
        material.type == searchParams.reportType
      )
    }

    if (searchParams.status !== '' && searchParams.status !== undefined) {
      filteredMaterials = filteredMaterials.filter(material =>
        material.status == searchParams.status
      )
    }

    // 分页处理
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    reports.value = filteredMaterials.slice(start, end)
    pagination.total = filteredMaterials.length
  } catch (error) {
    ElMessage.error('获取报告列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = ''
  searchParams.reportType = ''
  searchParams.status = ''
  pagination.currentPage = 1
  fetchReports()
}

// 分页处理
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchReports()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchReports()
}

// 查看报告详情
const viewReportDetail = async (material) => {
  try {
    const response = await teacherStore.getMaterialDetail(material.id)
    selectedReport.value = response
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取报告详情失败: ' + (error.response?.data?.message || error.message))
  }
}

// 审核报告
const reviewReport = (material) => {
  selectedReport.value = material
  reviewForm.status = 1
  reviewForm.rejectReason = ''
  reviewForm.comment = ''
  reviewDialogVisible.value = true

  // 清除验证状态
  nextTick(() => {
    if (reviewFormRef.value) {
      reviewFormRef.value.clearValidate()
    }
  })
}

// 提交审核
const submitReview = async () => {
  if (!reviewFormRef.value) return

  await reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      reviewLoading.value = true
      try {
        const data = {
          status: reviewForm.status,
          ...(reviewForm.status === 2 && { rejectReason: reviewForm.rejectReason }),
          comment: reviewForm.comment
        }

        await teacherStore.reviewMaterial(selectedReport.value.id, data)
        ElMessage.success('审核成功')
        reviewDialogVisible.value = false
        fetchReports()
      } catch (error) {
        ElMessage.error('审核失败: ' + (error.response?.data?.message || error.message))
      } finally {
        reviewLoading.value = false
      }
    }
  })
}

// 获取报告类型标签
const getReportTypeLabel = (type) => {
  switch (type) {
    case 1: return '周志'
    case 2: return '实习报告'
    case 3: return '成果展示'
    default: return '未知'
  }
}

// 获取报告状态标签
const getReportStatusLabel = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

// 获取报告状态类型
const getReportStatusType = (status) => {
  switch (status) {
    case 0: return ''
    case 1: return 'success'
    case 2: return 'danger'
    default: return ''
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

onMounted(() => {
  fetchReports()
})
</script>

<style scoped>
.header {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.report-detail {
  margin-bottom: 20px;
}

.content-section {
  margin-top: 20px;
}

.content-section h3 {
  margin-bottom: 10px;
}

.report-content {
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  min-height: 100px;
}

.file-section {
  margin-top: 20px;
}

.file-section h3 {
  margin-bottom: 10px;
}
</style>
